package com.permissionx.gjx

import androidx.fragment.app.FragmentActivity

object PermissionX {
    private const val TAG = "InvisibleFragment"

    /**
     *
     * @param activity FragmentActivity
     * @param permissions Array<out String> 需要的权限列表
     * @param callback Function2<Boolean, List<String>, Unit> 回调方法，参数表示allGranted和deniedList
     */
    fun request(
        activity: FragmentActivity, vararg permissions: String, callback:
        PermissionCallback
    ) {
        val fragmentManager = activity.supportFragmentManager
        val existedFragment =
            fragmentManager.findFragmentByTag(TAG) // 判断这个Activity是不是已经有InvisibleFragment了
        val fragment = if (existedFragment != null) {
            existedFragment as InvisibleFragment
        } else {
            // 如果现在Activity中没有InvisibleFragment
            val invisibleFragment = InvisibleFragment()
            // 添加InvisibleFragment
            fragmentManager.beginTransaction().add(invisibleFragment, TAG).commitNow()
            // 返回这个InvisibleFragment
            invisibleFragment
        }
        // 调用InvisibleFragment里的权限请求逻辑
        // * 表示将一个数组转换成可变长度参数传递过去
        fragment.requestNow(callback, *permissions)
    }
}